package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao{
    @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;
        Statement stat = null;
        String sql = "select * from tb_goods";
        ResultSet resultSet = null;
        try {
            conn = dataSource.getConnection();
            stat = conn.createStatement();
            resultSet = stat.executeQuery(sql);
            List<Map<String, Object>> list = new ArrayList<>();
            while (resultSet.next()) {
                list.add(rowMap(resultSet));
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            close(resultSet,stat,conn);
        }
    }

    private void close(ResultSet resultSet,Statement stat, Connection conn) {
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stat!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    private Map<String, Object> rowMap(ResultSet resultSet) throws SQLException {
        Map<String,Object> rowMap = new HashMap<>();
        ResultSetMetaData rsmd= resultSet.getMetaData();
        int columnCount = rsmd.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
            rowMap.put(rsmd.getColumnLabel(i+1), resultSet.getObject(rsmd.getColumnLabel(i+1)));
        }
        return rowMap;
    }
}
